package com.lifp.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.auth.DevAuth;
import com.lifp.config.BaiDuAiRestFaceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @Description TODO
 * @Author lifp
 * @Date 2023/2/24
 * @Version 1.0
 */
@Component
public class FaceTokenUtil {
    @Autowired
    private BaiDuAiRestFaceConfig config;
    @Autowired
    private RedisTemplate redisTemplate;

    private final String  ACCESS_TOKEN_CACHE_KEY = "BAIDU:FACE:ACCESS_TOKEN";

    //获取token
    public String getToken() {
        //token 有效期为30天，可以缓存在redis
        String tokenFromRedis = getTokenFromRedis();
        if(tokenFromRedis != null){
            return tokenFromRedis;
        }

        String oauthStr = DevAuth.oauth(config.getApiKey(), config.getSecretKey(), null).toString();

        JSONObject object = JSONUtil.parseObj(oauthStr);

        if(object != null){
            String access_token = (String) object.get("access_token");
            Integer expires_in = (Integer) object.get("expires_in");

            redisTemplate.opsForValue().set(ACCESS_TOKEN_CACHE_KEY,access_token,Duration.ofSeconds(expires_in-10));

            return access_token;
        }
        return null;
    }

    private String getTokenFromRedis(){
        String token = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_CACHE_KEY);
        return token;
    }
}
